package com.joke.mydiary.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import com.joke.mydiary.MainActivity;
import com.joke.mydiary.pojo.Diary;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import java.io.File;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * 用于网络备份
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class BackupIntentService extends IntentService {

    private NotificationCompat.Builder notifiBuilder;
    private NotificationManager mNotificationManager;

    public BackupIntentService() {
        super("BackupIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            String str = intent.getStringExtra("userName");
            String uriPath = intent.getStringExtra("uriPath");
            String userName = null;
            Diary diary = (Diary) intent.getSerializableExtra("diary");

            //处理用户名：+8618600001234
            if (str.contains("+")) {
                userName = str.substring(3);
            } else {
                userName = str;
            }
            if (uriPath.contains("127.0.0.1")) {

                notifiBuilder = new NotificationCompat.Builder(this);
                notifiBuilder.setSmallIcon(android.R.drawable.ic_dialog_info)
                        .setContentTitle("云备份")
                        .setContentText("服务器错误，请在设置中输入正确的服务器IP")
                        .setDefaults(Notification.DEFAULT_ALL);
                Intent resultInent = new Intent(this, MainActivity.class);
                PendingIntent pi = PendingIntent.getActivity(this, 0, resultInent, PendingIntent.FLAG_UPDATE_CURRENT);
                notifiBuilder.setContentIntent(pi);

                mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                // mId allows you to update the notification later on.
                mNotificationManager.notify(0x1, notifiBuilder.build());

                return;
            }
            //网络处理
            HttpPost post = new HttpPost("http://" + uriPath + "/AndroidService/ReceiveServlet");
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            HttpClient httpclient = new DefaultHttpClient();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String date = sdf.format(diary.getDate());

                FileBody fileBody = null;
                if (diary.getImagePath() != null && !"".equals(diary.getImagePath().trim())) {
                    File file = new File(diary.getImagePath());
                    fileBody = new FileBody(file);
                }

                StringBody parameterName = new StringBody(userName, Charset.forName("UTF-8"));
                StringBody parameterDate = new StringBody(date, Charset.forName("UTF-8"));
                StringBody parameterContent = new StringBody(diary.getContent(), Charset.forName("UTF-8"));

                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
                entity.addPart("userName", parameterName);
                entity.addPart("date", parameterDate);
                entity.addPart("content", parameterContent);
                if (fileBody != null) {
                    entity.addPart("image", fileBody);
                }
                post.setEntity(entity);
                HttpResponse response = httpclient.execute(post);


                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    notifiBuilder = new NotificationCompat.Builder(this);
                    notifiBuilder.setSmallIcon(android.R.drawable.ic_menu_upload)
                            .setContentTitle("云备份")
                            .setContentText("您的备忘录已完成云备份，点击查看")
                            .setDefaults(Notification.DEFAULT_ALL);
                    Intent resultInent = new Intent(this, MainActivity.class);
                    PendingIntent pi = PendingIntent.getActivity(this, 0, resultInent, PendingIntent.FLAG_UPDATE_CURRENT);
                    notifiBuilder.setContentIntent(pi);
                    mNotificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    // mId allows you to update the notification later on.
                    mNotificationManager.notify(0x1, notifiBuilder.build());
                    httpclient.getConnectionManager().shutdown();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


}
